<?php
/**
 * Created by PhpStorm.
 * User: hgq
 * Date: 2016/6/13 0013
 * Time: 下午 2:39
 */
namespace app\librarys;

/**
 * 调用第三方系统接口
 * Class Inteface
 * @package app\models
 */
class Inteface
{
//    /**
//     * 业务系统接口地址
//     * @return string
//     */
//    private static function BossServiceAddress()
//    {
//        return \Yii::$app->params['inteface.BossServiceAddress'];
//    }
//
//    /**
//     * 向业务系统下订单
//     * @param $orderData
//     * {
//     *   'orderCode':'订单编号',
//     *   'ordertype':''integral,
//     *   'shrName':'收货人姓名',
//     *   'sheng':'省名称',
//     *   'shi':'市名称',
//     *   'qu':'区名称',
//     *   'address':'收货地址',
//     *   'mobile':'收货人手机号码',
//     *   'deskphone':'',
//     *   'email':''',
//     *   'amount':0,
//     *   'custname':机构名称,
//     *   'goods':
//     *   [
//     *     {
//     *       'goods_code':'商品编码',
//     *       'goods_name':'商品名称',
//     *       'goods_number':商品数量,
//     *       'price':0
//     *     }
//     *   ]
//     * }
//     * @return mixed
//     * {
//     *   "status":"1",
//     *   "info":"生成出库任务以及订单成功",
//     *   "data":null
//     * }
//     */
//    public static function setOrder($orderData)
//    {
//        $client = new \SoapClient(self::BossServiceAddress(), array('encoding' => 'GBK'));
//        $param = array('orderData' => json_encode($orderData));
////        $param = array('orderData'=>'{"orderCode":"W14031304000002","shrName":"测试收货人","sheng":"重庆市","shi":"市辖区(重庆市)","qu":"巴南区","address":"渔洞24号中","mobile":"13452467858","deskphone":"0238665485","email":"","amount":"12000.00","goods":[{"goods_code":"DLHCJ0001","goods_name":"麦森艾丽斯汤锅--20cm绿色","goods_number":1,"price":122.67}]}');
//
//        $arr5 = $client->setOrder($param);
//        $tmp = $arr5->setOrderReturn;
//        $tmp = iconv('GBK', 'UTF-8', $tmp);
//
//        return json_decode($tmp);
//    }
//
//    /**
//     * 从业务系统获取所有产品数据
//     * @return mixed
//     */
//    public static function getGoodsList($pageIndex, $pageCount)
//    {
//        $client = new \SoapClient(self::BossServiceAddress(), array('encoding' => 'GBK'));
//        $param = array('pageIndex' => $pageIndex, 'pageCount' => $pageCount);
//        $response = $client->getAllGoods($param);
//        $tmp = $response->getAllGoodsReturn;
//        $tmp = iconv('GBK', 'UTF-8', $tmp);
//
//        return json_decode($tmp, true);
//    }
//
//    /**
//     * 从业务系统获取所有产品图片数据
//     * @return mixed
//     */
//    public static function getGoodsImgList()
//    {
//        $client = new \SoapClient(self::BossServiceAddress(), array('encoding' => 'GBK'));
//
//        $response = $client->getGoodsImage();
//        $tmp = $response->getGoodsImageReturn;
//        $tmp = iconv('GBK', 'UTF-8', $tmp);
//
//        return json_decode($tmp, true);
//    }
//
//    /**
//     * 从业务系统获取所有产品分类数据
//     * @return mixed
//     */
//    public static function getGoodsCategoryList()
//    {
//        $client = new \SoapClient(self::BossServiceAddress(), array('encoding' => 'GBK'));
//
//        $response = $client->getGoodsCategory();
//        $tmp = $response->getGoodsCategoryReturn;
//        $tmp = iconv('GBK', 'UTF-8', $tmp);
//
//        return json_decode($tmp, true);
//    }
//
//
//    /**
//     * 根据商品code获取库存
//     * @param $goodscode
//     * @return mixed
//     */
//    public static function getGoodsStock($goodscode)
//    {
//        $client = new \SoapClient(self::BossServiceAddress(), array('encoding' => 'GBK'));
//        $param = array('giftCode' => $goodscode);
//        $response = $client->getGiftStock($param);
//        $tmp = $response->getGiftStockReturn;
//        $tmp = iconv('GBK', 'UTF-8', $tmp);
//
//        return json_decode($tmp);
//    }
//
//    /**
//     * 注册机构
//     * @param $record
//     * @return mixed
//     */
//    public static function setInstitutionCode($record)
//    {
//        $client = new \SoapClient(self::BossServiceAddress(), array('encoding' => 'GBK'));
//        $Institution=[
//            "instname"=>$record['name'],
//            "address"=>$record['address']
//            ];
//        $param = array('infoJson'=>json_encode($Institution));
//
//        $arr5 = $client->createCust($param);
//        $tmp = $arr5->createCustReturn;
//        $tmp = iconv('GBK', 'UTF-8', $tmp);
//
//        return json_decode($tmp);
//    }

    public static function sendSms($to, $templateId, $data)
    {
        $responseString = Tools::postJson(self::_getSmsRequestUrl(), ['to' => $to, 'template_id' => $templateId, 'data' => $data]);
        $response = json_decode($responseString);
        return $response;
    }

    private static function _getSmsRequestUrl()
    {
        $account = self::_getSmsApiAccount();
        $token = self::_getSmsApiToken();
        $timestamp = time();
        $sign = hash_hmac('sha256', $account . $token . $timestamp, $token);
        $address = self::_getSmsApiAddress();
        $url = $address . '?account=' . $account . '&timestamp=' . $timestamp . '&sign=' . $sign;

        return $url;
    }

    private static function _getSmsApiAddress()
    {
        return \Yii::$app->params['inteface.sms.address'];
    }

    private static function _getSmsApiAccount()
    {
        return \Yii::$app->params['inteface.sms.account'];
    }

    private static function _getSmsApiToken()
    {
        return \Yii::$app->params['inteface.sms.token'];
    }


    //--------------------------------Boss Api-------------------------------------------------------------------------------//
    /**
     * 向业务系统下订单
     * @param $orderData
     * {
     *   'orderCode':'订单编号',
     *   'ordertype':''integral,
     *   'shrName':'收货人姓名',
     *   'sheng':'省名称',
     *   'shi':'市名称',
     *   'qu':'区名称',
     *   'address':'收货地址',
     *   'mobile':'收货人手机号码',
     *   'deskphone':'',
     *   'email':''',
     *   'amount':0,
     *   'custname':机构名称,
     *   'goods':
     *   [
     *     {
     *       'goods_code':'商品编码',
     *       'goods_name':'商品名称',
     *       'goods_number':商品数量,
     *       'price':0
     *     }
     *   ]
     * }
     * @return mixed
     * {
     *   "status":"1",
     *   "info":"生成出库任务以及订单成功",
     *   "data":null
     * }
     */
    public static function setOrder($orderData)
    {
        $data = [
            'orderData' => $orderData
        ];
        return self::_getResponseData('set-order', $data);
    }

    /**
     * 从业务系统获取所有产品数据
     * @return mixed
     */
    public static function getGoodsList($pageIndex, $pageCount, $isSynAllinfo)
    {
        $data = [
            'pageIndex' => $pageIndex,
            'pageCount' => $pageCount,
            'isSynAllinfo' => $isSynAllinfo
        ];
        return self::_getResponseData('get-all-goods', $data);

    }

    /**
     * 将客户剩余积分发送至中国人寿接口
     * @param $phone
     * @param $integral
     */
    public static function sendIntegraltoCqChianLife($phone,$integral)
    {
        $data = [
            'mobile' => $phone,
            'current_point' => $integral,
            'username' => 'Point%u946B%u6CF0gs'
        ];


        //密钥
        $keyStr = 'xintai22eac4488ca3143chinalifecq';
        //加密的字符串
//        $plainText = 'test';

//        $aes = new CryptAES();
//        $aes->set_key($keyStr);
//        $aes->require_pkcs5();
//        $encText = $aes->encrypt($data);
//        var_dump('x1');


        $responseString = Tools::postJsonForAes('http://cqwx.e-chinalife.com/cqyy/api/VipPointChange/UpdateVipCustPointSercet',$data,$keyStr);
//        $responseString = Tools::postJson('http://cqwx.e-chinalife.com/cqyy/api/VipPointChange/UpdateVipCustPoint', $data);
//        echo $responseString;
//        $response = json_decode($responseString);

        return $responseString;
    }


    /**
     * 从业务系统获取所有产品图片数据
     * @return mixed
     */
    public static function getGoodsImgList()
    {
        return self::_getResponseData('get-goods-image', null);
    }

    /**
     * 从业务系统获取所有产品分类数据
     * @return mixed
     */
    public static function getGoodsCategoryList()
    {
        return self::_getResponseData('get-goods-category', null);
    }


    /**
     * 根据商品code获取库存
     * @param $goodscode
     * @return mixed
     */
    public static function getGoodsStock($goodscode)
    {
        $data = ['goodscode' => $goodscode];
        return self::_getResponseData('get-goods-stock', $data);
    }


    /**
     * 根据去单号取得物流跟踪记录
     * @param $expressNumber
     * @return mixed
     */
    public static function getExpressTrackRecord($expressNumber)
    {
        $data = ['expressNumber' => $expressNumber];
        return self::_getResponseData('get-express-track-record', $data);
    }

    /**
     * 注册机构
     * @param $record
     * @return mixed
     */
    public static function setInstitutionCode($record)
    {
//        $data = [
//            'name' => $record['name'],
//            'address' => $record['address']
//        ];
//        return self::_getResponseData('set-institution-code', $data);

        $data = [
            'name' => $record['name'],
            'address' => $record['address']
        ];
        $response = self::_getResponse('set-institution-code', $data);
        return $response;
    }

    /**
     * 根据删除NC中已经建立的机构
     * @param $code
     * @return mixed
     */
    public static function delInstitutionCode($code)
    {
        $data = [
            'instcode' => $code
        ];
        $response = self::_getResponse('del-institution-code', $data);
        return $response;
    }

    /**
     * 查询物流信息
     * @param string $logisticsCode 快递单号
     * @return mixed
     * @throws \Exception
     */
    public static function getLogistics($logisticsCode)
    {
        $data = ['expressNumber' => $logisticsCode];

        return self::_getResponseData('get-express-track-record', $data);
    }


    private static function _getResponseData($apiName, $data)
    {

        $response = self::_getResponse($apiName, $data);
        if ($response->status == 0) {
            return $response->data;
        } else {
            throw new \Exception($apiName.'--'.$response->message, $response->status);
        }
    }


    private static function _getResponse($apiName, $data)
    {
        $responseString = Tools::postJson(self::_getRequestUrl($apiName), $data);
        $response = json_decode($responseString);
        return $response;
    }

    private static function _getRequestUrl($apiName)
    {
        $account = self::_getApiAccount();
        $token = self::_getApiToken();
        $timestamp = time();
        $sign = hash_hmac('sha256', $account . $token . $timestamp, $token);
        $address = self::_getApiAddress();
        $url = $address . $apiName . '?account=' . $account . '&timestamp=' . $timestamp . '&sign=' . $sign;

        return $url;
    }

    private static function _getApiAddress()
    {
        return \Yii::$app->params['inteface.bossapi.address'];
    }

    private static function _getApiAccount()
    {
        return \Yii::$app->params['inteface.bossapi.account'];
    }

    private static function _getApiToken()
    {
        return \Yii::$app->params['inteface.bossapi.token'];
    }
    //--------------------------------Boss Api-------------------------------------------------------------------------------//

    public static function getNcGoodsTag()
    {
        $data = [];
        return self::_getResponseData('get-goods-exte-category', $data);
    }
    public static function getNcGoodsTagGoods()
    {
        $data = [];
        return self::_getResponseData('get-all-goods-extecate', $data);
    }

}